// server.js
const path = require('path');
const fs = require('fs');
const express = require('express')
const server = require('express')()
const proxy = require('http-proxy-middleware');
const history = require('connect-history-api-fallback');
const ecstatic = require('ecstatic');

const WWW_DIR = path.resolve(__dirname + '../../../');
const serverPath = require('./config/server.json');

let routes = require('./config/route.json').routes;
let THEME;

const reduce = function(list){
  let hash = {};
  list = list.reduce(function(item, next) {
    hash[next.path] ? '' : hash[next.path] = true && item.push(next);
    return item;
  }, [])
  return list;
};

// 加载当前theme
const getTheme = function() {
  THEME = fs.readFileSync(WWW_DIR + '/www-themes/theme.local', 'utf8').trim();
};

const getPath = function(fileName) {
  console.log('fileName => ', fileName);
  let path;

  // if (/\/view\/(.*?)/.test(fileName)) {
  //   path = WWW_DIR + '/www-fe/dist/app.html'
  //   console.log('path 1 => ', path)
  // } else {
  //   path = WWW_DIR + '/www-themes/' + THEME + '-fe/dist/modules' + fileName + '.html';
  //   console.log('path 2 => ', path)
  //
  //   // 如果券商下没有定制化 则寻找www-fe的头尾文件
  //   if (!fs.existsSync(path)) {
  //     path = WWW_DIR + '/www-fe/dist/modules' + fileName + '.html'
  //
  //     // 如果www-fe下也不存在 则指向module/app.html
  //     if (!fs.existsSync(path)) {
  //       fileName = '/' + fileName.replace('/view', '').split('/')[1] + '/index';
  //     };
  //     path = WWW_DIR + '/www-fe/dist/modules' + fileName + '.html'
  //   };
  // }

  if (/\/view\/(.*?)/.test(fileName)) {

    // 如果券商下有app.html 则加载theme的
    if (fs.existsSync(WWW_DIR + '/www-themes/' + THEME + '-fe/dist/app.html')) {
      path = WWW_DIR + '/www-themes/' + THEME + '-fe/dist/app.html'
    } else {
      path = WWW_DIR + '/www-fe/dist/app.html'
    }
    console.log('path => ', path)
  }

  //  else {
  //   // path = WWW_DIR + '/www-themes/' + THEME + '-fe/dist/modules' + fileName + '.html';
  //   // console.log('path 2 => ', path)
  //   //
  //   // // 如果券商下没有定制化 则寻找www-fe的头尾文件
  //   // if (!fs.existsSync(path)) {
  //   //   path = WWW_DIR + '/www-fe/dist/modules' + fileName + '.html'
  //   //
  //   //   // 如果www-fe下也不存在 则指向module/app.html
  //   //   if (!fs.existsSync(path)) {
  //   //     fileName = '/' + fileName.replace('/view', '').split('/')[1] + '/index';
  //   //   };
  //   //   path = WWW_DIR + '/www-fe/dist/modules' + fileName + '.html'
  //   // };
  // }

  return path;
}

// 加载头尾文件
const getIncludePath = function(fileName) {
  let path = WWW_DIR + '/themes/' + THEME + '-fe/dist/asset/' + fileName;

  // 如果券商下没有定制化 则寻找www-fe的头尾文件
  if (!fs.existsSync(path)) {
    path = WWW_DIR + '/www-fe/dist/asset/' + fileName
  };
  // console.log('getIncludePath => ', path);
  return path;
}

const renderHtml = function(fileName) {
  const includeAllReg = /@@include\([\'|\"]([\w.|\/]*)[\'|\"]\)/g;
  const includeReg = /@@include\([\'|\"]([\w.|\/]*)[\'|\"]\)/;
  const versionReg = /{{version}}/g;
  const cdnReg = /{{cdnPath}}/g;
  const imgReg = /{{imgPath}}/g;
  const fileReg = /{{filePath}}/g;
  const tokenReg = /{{token}}/g;
  const themesReg = /{{projectTheme}}/g;

  let emptyHtml = fs.readFileSync(getPath(fileName), 'utf8');

  // console.log('emptyHtml => ', emptyHtml);
  let version = fs.readFileSync('./version.txt', 'utf8');
  let includeList = emptyHtml.match(includeAllReg);

  includeList && includeList.map((include, index) => {
    let includeFile = fs.readFileSync(getIncludePath(include.match(includeReg)[1]), 'utf8');
    emptyHtml = emptyHtml.replace(include.match(includeReg)[0], includeFile);
  })
  console.log(THEME)
  emptyHtml = emptyHtml.replace(versionReg, version);
  emptyHtml = emptyHtml.replace(cdnReg, '');
  emptyHtml = emptyHtml.replace(imgReg, serverPath.CDN_DOMAIN);
  emptyHtml = emptyHtml.replace(fileReg, serverPath.FILE_DOMAIN);
  emptyHtml = emptyHtml.replace(themesReg, THEME);
  emptyHtml = emptyHtml.replace(tokenReg, '600519');

  // console.log('emptyHtml', emptyHtml);
  return emptyHtml;
}

// 设置静态资源
server.get(getTheme())


// 循环生成路由
routes.map(item => {
  server.get((item.alias || item.path), (req, res) => {

    if (item.alias) {
      req.route.path = item.path;
    };

    req.route.path = req.route.path.replace(/([A-Z])/g,"-$1").toLowerCase();
    console.log('req.route.path => ', req.route.path);
    res.send(renderHtml(req.route.path));
  })
})

server.use(
  history({
    verbose: true,
    logger: console.log.bind(console),
    rewrites: [
      {
        from: /^\/std\/dist\/asset\/(.*?).*/,
        to: function(context) {
          return context.parsedUrl.pathname.replace('/std/dist/asset', '/asset')
        }
      },

      {
        from: /^\/std\/dist\/modules\/(.*?).*/,
        to: function(context) {
          return context.parsedUrl.pathname.replace('/std/dist/modules', '/modules')
        }
      },

      {
        from: /^\/std\/dist\/(.*?).*/,
        to: function(context) {
          return context.parsedUrl.pathname.replace('/std/dist', '')
          // console.log('serverPath.SERVER_DOMAIN => ', [serverPath.SERVER_DOMAIN, context.parsedUrl.pathname].join(''))
          // return [serverPath.SERVER_DOMAIN, context.parsedUrl.pathname].join('')
        }
      },

      {
        from: new RegExp('^\/themes\/' + THEME + '\/static\/dist\/(.*?).*'),
        to: function(context) {
          return context.parsedUrl.pathname
          .replace('/static/dist', '')
          .replace('/themes', '/www-themes')
          .replace('/' + THEME, '/' + THEME + '-fe')
        }
      },

      {
        from: /\/view\/(.*?)/,
        to: function(context) {
          return '/dist/app.html'
        }
      }
      // ,
      //
      // {
      //   from: /\/(.*?)/,
      //   to: function(context) {
      //     // console.log('serverPath.SERVER_DOMAIN => ', [serverPath.SERVER_DOMAIN, context.parsedUrl.pathname].join(''))
      //     return [serverPath.SERVER_DOMAIN, context.parsedUrl.pathname].join('')
      //   }
      // }
    ]
  })
);

// 对std下的静态文件进行加载
server.use(ecstatic({
  root: path.resolve('../dist'),
  baseDir: '/'
}));

// 对theme下的静态文件进行加载
server.use(ecstatic({
  root: path.resolve('../../www-themes/' + THEME + '-fe/dist'),
  baseDir: '../www-themes/' + THEME + '-fe/'
}));

server.get(function() {
  let themesRoutes = [];

  if (fs.existsSync(WWW_DIR + '/www-themes/' + THEME + '-fe/tools/config/route.json')) {
    themesRoutes = require(WWW_DIR + '/www-themes/' + THEME + '-fe/tools/config/route.json').routes;
  };

  routes = reduce(routes.concat(themesRoutes));
  // console.log(routes);
}())


// 请求转发
// 不包含 std/dist 的都请求服务器 因为是接口
// 包含static/dist 的都访问本地 因为是静态资源
server.use('/*.css', proxy({
  target: serverPath.CDN_DOMAIN,
  changeOrigin: true
}));

server.use('/*.js', proxy({
  target: serverPath.CDN_DOMAIN,
  changeOrigin: true
}));

server.use('/*.png', proxy({
  target: serverPath.CDN_DOMAIN,
  changeOrigin: true
}));

server.use('/', proxy({
  target: serverPath.SERVER_DOMAIN,
  changeOrigin: true
}));

console.log('ndoe server http://127.0.0.1:9000')
server.listen(9000)
